import React,{Component} from 'react'
import Pages from '../Pages'
import {Link} from 'react-router'
import { Spin,message,Button} from 'antd';
import * as pub from '../../config/public';
import * as fetch from '../../config/fetch';
import Layer from '../Layer';
import $ from 'jquery';
import Dropzone from 'react-dropzone';
class ImagItem extends Component {
     constructor(props) {
		super(props)
		this.state = {
			ImagItem:this.props.item,
			visibleDel:false,
			cover_imageBJ:this.props.cover_imageBJ?this.props.cover_imageBJ:[]
		}
	 }
	 componentWillReceiveProps(nextProps) {
		 this.setState({
			 cover_imageBJ:nextProps.cover_imageBJ
		 })
	 }
	 onMouseOver(){
       this.setState({
		   visibleDel:true
	   })
	}	
	onMouseOut(){
       this.setState({
		   visibleDel:false
	   })
	}
	// DeleteImg(value){
	// 	this.props.handleImg(value);
	// }
	DeleteImgPath(value,value1){
		if(value1){
          this.props.handleImgPath(value);
		}else{
          this.props.handleImg(value);  
		}
	}
	 render(){
	
		 return(
			 
             /*<div>
				 {
					 this.state.cover_imageBJ.length===0?
                     <li key={this.props.index} id={`image${this.props.index}`} onClick={()=>this.DeleteImg(this.props.index)}><img src={this.props.item.preview} onMouseOver={this.onMouseOver.bind(this)}  onMouseOut={this.onMouseOut.bind(this)} alt="我的蜂行圈"/>
			             {this.state.visibleDel?
				                <span  className="trash" >删除</span>:null
			             }
			         </li>:
					 <li key={this.props.index}><img src={pub.getFile(this.props.item.essayPhotoPath)} alt="我的蜂行圈"/></li>
				 }
			 </div>*/
            <div>
					 <li key={this.props.index} id={`image${this.props.index}`} onClick={()=>this.DeleteImgPath(this.props.index,this.props.item.essayPhotoPath)}><img src={this.props.item.essayPhotoPath?pub.getFile(this.props.item.essayPhotoPath):this.props.item.preview} onMouseOver={this.onMouseOver.bind(this)} onMouseOut={this.onMouseOut.bind(this)} alt="我的蜂行圈"/>
					     {this.state.visibleDel?
				                <span  className="trash" >删除</span>:null
			             }
					 </li>
			 </div>
		 )
	 }
}
class ArticleManage extends Component {
	constructor(args) {
		super()
		this.state = {
			jumpPage: 1,
			essayList: [],
			totalPage: 0,
			loading: false,
			visible:false,
			checkState:'',
			essayTitle:'',
			cover_image:[],
			essayNote:'',
			visibleDH:false,
			essayId:'',
			essayTitleDH:'',
			cover_imageBJ:[],
			showLayer:false,
			deleteArticleId:''
		}
			
	}
	componentWillMount() {
		this.show();
	}
	showModal = () => {
		this.setState({
			visible: true,
		});
	}
	hideMdoal = (e) => {
		$('.layer').addClass('layer-anim-close');
		setTimeout(() => {
			this.setState({
				essayNote:'',
				essayTitle:'',
				cover_image:[],
				visible: false,
				essayId:''
			},()=>{
				$('.layer').removeClass('layer-anim-close');
			});
			
		}, 50);
	}
	hideModelDH = (e) => {
		$('.layer').addClass('layer-anim-close');
		setTimeout(() => {
			this.setState({
				essayId:'',
				essayTitleDH:'',
				visibleDH: false,
			},()=>{
				$('.layer').removeClass('layer-anim-close');
			});
			
		}, 50);
	}
	onSubmit=(value)=>{
		let formData = new FormData();
		if(this.state.essayTitle.replace(/^ +| +$/g,'')===""){
             message.error('请输入文章标题');
		}else{
			formData.append('essayTitle',this.state.essayTitle);
		}
		if(this.state.essayNote.replace(/^ +| +$/g,'')===""){
             message.error('请输入文章内容');
		}else{
			formData.append('essayNote',this.state.essayNote);
		}
		// formData.append('essayNote',this.state.essayNote);
		formData.append('checkState',value);
		if(this.state.texts==='编辑文章'){
            formData.append('essayId',this.state.essayId);
			for(let x of this.state.cover_imageBJ){
			    formData.append('photoPath',x.essayPhotoPath);
		    }
		}
		for(let x of this.state.cover_image){
			formData.append('file',x);
		}
		if(this.state.essayId!==""){
			formData.append('operationState','U');
		}
		if(this.state.essayTitle.replace(/^ +| +$/g,'')!==""&&this.state.essayNote.replace(/^ +| +$/g,'')!==""){
			pub.loading(this,true);
			fetch.insertorupdate(formData).then((data)=>{
				this.setState({
					essayTitle:'',
					essayNote:'',
					cover_image:[],
					visible:false  
				},()=>{
				  this.show();
				})
				pub.loading(this,false);
			}, (res) => {
				pub.loading(this,false);
				pub.reject(res);
			})
		}
		
			
	}
	show() {
		pub.loading(this, true);
		fetch.articleManage(this.state.jumpPage,this.state.checkState,this.state.essayTitle).then((data) => {
			this.setState({
				essayList: data.essayList?data.essayList:[],
				totalPage: data.totalPage
			}, () => {
				pub.loading(this, false);
			})
		}, (res) => {
			pub.loading(this, false);
			pub.reject(res);
		})
	}
	jump(page) {
		this.setState({
			jumpPage: page
		},()=>{
			this.show()
		})
	}
	numberInput = (e) => {
			this.refs.redeemValue.value = this.refs.redeemValue.value.replace(/[^\d]/g,'');
	} 		
	setDH(value) {
		pub.loading(this, true);
		if(value.exchangeIntegral !==undefined){
			if(this.refs.redeemValue.value===''){
				message.error("不能为空");
				pub.loading(this, false);
				return
			}if(isNaN(this.refs.redeemValue.value)){
				message.error("兑换积分必须为数字");
				pub.loading(this, false);
				return
			}
			else{
				this.refs.redeemValue.value = this.refs.redeemValue.value.replace(/[^\d]/g,'');
			}
		}
			
		
		fetch.setGoodArticle(value).then((data) => {
			if(data.result === 'RC100'){
				this.show();
				this.setState({
					visibleDH: false,
				})
			}else{
				message.error(data.errMsg,3);
			}
			pub.loading(this, false);
		}, (res) => {
			pub.reject(res);
			pub.loading(this, false);
		})
	}
	search(){
		this.show();
	}
	del(id){
		pub.loading(this, true);
		fetch.delArticle(id).then((data)=>{
			if(data.result === 'RC100'){
				this.show();
			}else{
				message.error(data.errMsg,3);
			}
			pub.loading(this, false);
		}, (res) => {
			pub.loading(this, false);
			pub.reject(res);
		})
	}
	chooseImage(accepted, rejected){
	//	if(this.state.texts==='新增文章'){
			if(accepted.length+this.state.cover_image.length+this.state.cover_imageBJ.length>9){
			   message.error('图片不能超过9张')
			}else{
				this.setState({
					cover_image:this.state.cover_image.concat(accepted),
				})
			}

		// }else{
        //   if(accepted.length>9){
		// 	message.error('图片不能超过9张')
		// }else{
		// 	this.setState({
		// 		cover_image:accepted,
		// 		cover_imageBJ:[]
		// 	})
		// }
		// }
	}
	editEssay(essayId){
			fetch.getSelectessay({essayId:essayId}).then((data)=>{
			let essayTitles=data.essay.essayTitle.replace(/(^\s*)|(\s*$)/g, "")===""?message.error('请输入文章标题'):data.essay.essayTitle;
			let essayNotes=data.essay.essayNote.replace(/(^\s*)|(\s*$)/g, "")===""?message.error('请输入文章内容'):data.essay.essayNote;
				this.setState({
					visible:true,
					essayTitle:essayTitles,
					essayNote: essayNotes,
					essayId  : data.essay.essayId,
					cover_imageBJ:data.essay.essayPhotos?data.essay.essayPhotos:[],
					texts:"编辑文章"
				})
			}, (res) => {
				pub.reject(res);
			})
	}
	deleteArticle(essayId){
		this.setState({
			visible:false
		},()=>{
            pub.loading(this,true);
			let formData = new FormData();
	        formData.append('essayId',essayId);
			formData.append('operationState','D');
			fetch.integralMall(formData).then((data)=>{
					pub.loading(this,false);
					this.myEssaylist();
				}, (res) => {
					pub.loading(this,false);
					pub.reject(res);
				})
		   })	
	}
	inputValue=(event)=>{
		if(event.target.value.length<=20){
			this.setState({essayTitle: event.target.value});
		}else{
			event.target.value="";
			message.warning('文章标题不能超过20字！')
		}
      
	}
	textareaValue=(event)=>{
       this.setState({essayNote: event.target.value});
	}
	handleImg(value){
		let image = this.state.cover_image;
		let data = [];
		for(let i in image){
			if(Number(i) !== Number(value)){
				data.push(image[i])
			}
		}
		this.setState({
			cover_image:data
		})
	}
	handleImgPath(value){
		let image = this.state.cover_imageBJ;
		let data = [];
		for(let i in image){
			if(Number(i) !== Number(value)){
				data.push(image[i])
			}
		}
		this.setState({
			cover_imageBJ:data
		})
	}
	setRedeem(essayId,essayTitle,goodEssay){
        if(goodEssay==="1"){
			this.setDH({essayId:essayId});
		}else{
			this.setState({
				visibleDH:true,
				essayTitleDH:essayTitle,
				essayId:essayId
			})
		}
	}
	addShow(){
		this.setState({
			visible:true,
			texts:"新增文章",
			essayTitle:'',
			essayNote: '',
			essayId  : '',
			cover_image:[],
			cover_imageBJ:[],
			
		})
		
		
	}
	//去除特殊符号
	// numberInputs=(e)=>{
	// 	let value = e.target.value;
	// 	e.target.value=value.replace(/[@#\$%￥\^&{}?/><\|[\]()（）【】{}《》\+\-\=\''“‘”’\*]+/g,'');
	// }
	// numberInput=(e)=>{
	// 	let value = e.target.value;
	// 	e.target.value=value.replace(/[@#\$%￥\^&{}?/><\|[\]()（）【】{}《》\+\-\=\''“‘”’\*]+/g,'');
	// }
	// Nowrop(){
	// 	let value=this.refs.essayTitle.value
	// 	console.log(4567,value) 
	// }
	//1上架2删除
	essayupordetlete(essayId,state){
		pub.loading(this,true);
		let body={};
		if(state===1){
			body={essayId,operationState:'A'}
		}else{
           body={essayId,operationState:'R'}
		}
		fetch.essayupordetlete(body).then((data)=>{
			if(data.result==='RC100'){
				pub.loading(this,false);
				this.show();
				this.setState({
					showLayer:false,
			        deleteArticleId:''
				})
			}else{
				message.error(data.errMsg, 3);
				this.setState({
					showLayer:false,
			        deleteArticleId:''
				})
			}
			}, (res) => {
				pub.loading(this,false);
				pub.reject(res);
				this.setState({
					showLayer:false,
			        deleteArticleId:''
				})
			})	
	}
	deleteArticleId(id){
		this.setState({
			showLayer:true,
			deleteArticleId:id
		})
	}
	deleteArticleIdhideModel(){
		this.setState({
			showLayer:false
		})
	}
	render() {
		let nowUsercode = pub.user.userCode;
		return (
			<div className="container">
				<div className="common-title">文章管理
					<div className="filter-search floatR">
						<input type="text"  onChange={(e)=>{this.setState({essayTitle:e.target.value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'')})}} placeholder="搜索"/>
						<a onClick={()=>this.search()} className="btn search-btn"><i className="icon-search"></i></a>
					</div>
				</div>
				<div className="row select-filter clearFix">
					<div className="floatL">
						<select value={this.state.checkState} onChange={(e)=>{this.setState({checkState:e.target.value},()=>{this.show();})}}>
							<option value=''>全部状态</option>
							<option value='1'>初审</option>
							<option value='2'>未通过</option>
							<option value='3'>审核中</option>
							<option value='4'>草稿</option>
							<option value='5'>终审</option>
							<option value='6'>下架</option>
							}
						</select>
					</div>
					<a className="btn btn-blue" onClick={()=>this.addShow()}>新增</a>
				</div>

				<div className="row pad-t-20">
				<Spin spinning={this.state.loading} tip="加载列表中...">
				<div style={{minHeight:'516px'}}>
				    {this.state.essayList.map((item,index)=>{
				    	return(
					         <div key={index} className="article-container bg-FFFFFF box-shadow" style={{paddingTop:'36px'}}>
					         	<div className="article-list article-list-1">
					         		<p className="title">{item.essayTitle}</p>
					         		<p className="content">{item.essayNote?pub.subString(item.essayNote,100):'没有文字'}</p>
					         		<p className="time">{pub.formatTimestamp(item.updateTime)}</p>
					         	</div>
                            {
                              (()=>{
								  switch (item.checkState){
									  case '1':
									  return(
										   <div className="operate">
						                  	<span className="">初审
						                  		{/*<div onClick={()=>this.set(item.essayId)} className={"jing"+(item.goodEssay==='1'?' active':'')}></div>*/}
												{/*<div onClick={()=>this.setRedeem(item.essayId,item.essayTitle,item.goodEssay)} className={"jing"+(item.goodEssay==='1'?' active':'')}></div>  */}
						                  	</span>
						                  	<div className="operate-btn">
												  {
													  (JSON.parse(localStorage.getItem('user')).manageCom).length===1?
													  <Link to={`/admin/ArticleExamine/${item.essayId}`} className="blue">审核</Link>:null
												  }
												<Link to={`/admin/ArticleDetail/${item.essayId}`} className="blue">查看</Link>
												{item.operationState==='D'&&(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="blue-1" onClick={()=>this.essayupordetlete(item.essayId,1)}>上架</a>:null}
											    {item.operationState==='D'&&(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="blue-1" onClick={()=>this.deleteArticleId(item.essayId)}>删除</a>:null}
						                  		{/*<a className="blue-1" onClick={()=>this.editEssay(item.essayId)}>编辑</a>*/}
						                  		{/*<a onClick={()=>this.del(item.essayId)} className="red">下架</a>*/}
						                  	</div>
						                  </div>
						                  );
									  case '2':
									  return(
										  <div className="operate"><span className="red">未通过</span>
											<div className="operate-btn">
												<Link to={`/admin/ArticleDetail/${item.essayId}`} className="blue">查看</Link>
												{nowUsercode===item.createUser?<a className="blue-1" onClick={()=>this.editEssay(item.essayId)}>编辑</a>:null}
												{nowUsercode===item.createUser?<a onClick={()=>this.del(item.essayId)} className="red">删除</a>:null}
												{item.operationState==='D'&&(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="blue-1" onClick={()=>this.essayupordetlete(item.essayId,1)}>上架</a>:null}
											    {item.operationState==='D'&&(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="blue-1" onClick={()=>this.deleteArticleId(item.essayId)}>删除</a>:null}
											</div>
											</div>
									  );
									  case '3':
									  return(
										   <div className="operate">
					         	       	<span className="blue">审核中</span>
					         	       	<div className="operate-btn">
											<Link to={`/admin/ArticleDetail/${item.essayId}`} className="blue">查看</Link>
					         	       		<Link to={`/admin/ArticleExamine/${item.essayId}`} className="blue">审核</Link>
                                            {item.operationState==='D'&&(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="blue-1" onClick={()=>this.essayupordetlete(item.essayId,1)}>上架</a>:null}
											{item.operationState==='D'&&(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="blue-1" onClick={()=>this.deleteArticleId(item.essayId)}>删除</a>:null}
					         	       	</div>
					         	       </div>
									  );
									  case '5':
									  return(
                                           <div className="operate">
						                  	<span className="">终审
						                  		{/*<div onClick={()=>this.setDH({essayId:item.essayId})} className={"jing"+(item.goodEssay==='1'?' active':'')}></div>*/}
												  {
													 (JSON.parse(localStorage.getItem('user')).manageCom).length===1? 
													 <div onClick={()=>this.setRedeem(item.essayId,item.essayTitle,item.goodEssay)} className={"jing"+(item.goodEssay==='1'?' active':'')}></div>:null
												  }
						                  	</span>
						                  	<div className="operate-btn">
												<Link to={`/admin/ArticleDetail/${item.essayId}`} className="blue">查看</Link>
												  {
													  (JSON.parse(localStorage.getItem('user')).manageCom).length===1&&item.operationState!=='D'?
													  <div><a className="blue-1" onClick={()=>this.editEssay(item.essayId)}>编辑</a><a onClick={()=>this.del(item.essayId)} className="red">下架</a></div>:null
												  }
												  {item.operationState==='D'&&(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="blue-1" onClick={()=>this.essayupordetlete(item.essayId,1)}>上架</a>:null}
											      {(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="blue-1" onClick={()=>this.deleteArticleId(item.essayId)}>删除</a>:null} 
						                  	</div>
						                  </div>
									  );
									  case '4':
									  return(
										  <div className="operate">
						                  	<span className="">草稿</span>
						                  	<div className="operate-btn">
												<Link to={`/admin/ArticleDetail/${item.essayId}`} className="blue">查看</Link>
												{nowUsercode===item.createUser?<a className="blue-1" onClick={()=>this.editEssay(item.essayId)}>编辑</a>:null}
												{nowUsercode===item.createUser?<a onClick={()=>this.del(item.essayId)} className="red">删除</a>:null}
												{item.operationState==='D'&&(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="blue-1" onClick={()=>this.essayupordetlete(item.essayId,1)}>上架</a>:null}
											    {item.operationState==='D'&&(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="blue-1" onClick={()=>this.deleteArticleId(item.essayId)}>删除</a>:null}
											</div>
						                  </div>
									  );
									  default :
										return(
											<div className="state"><span className="red">Error</span></div>
										);

							  }})()}
					         </div>
				    		)
				    })}
				    </div>
				    </Spin>
			<Layer 
				title = "兑换积分"
				show={this.state.visibleDH} 
				hide={(e)=>{this.setState({visibleDH:false,loading:false})}}
				width="400px"
				height="270px"
			>
					<div className="row">
							<div className="pop-box-1"  style={{textAlign:'left'}}>											
								<p style={{paddingLeft:'50px'}}>文章名称：{this.state.essayTitleDH}</p>											
								<p style={{paddingLeft:'50px'}}>兑换积分：<input placeholder="设置兑换积分" ref="redeemValue" onKeyUp={this.numberInput} style={{height: "30px",border: "1px solid #eee"}} type="text"/></p>																				
							</div>
							<div className="pop-btn">
								<Button loading={this.state.loading} onClick={()=>this.hideModelDH()} className="btn btn-blue"  style={{borderRadius: '5px',marginRight:'50px'}}>取消</Button>
								<Button loading={this.state.loading} className="btn btn-blue" style={{borderRadius: '5px'}} onClick={()=>this.setDH({essayId:this.state.essayId,exchangeIntegral:this.refs.redeemValue.value})}>确认</Button>
							</div>
						</div>
			</Layer>		
			<Layer
				title = {this.state.texts}
				show={this.state.visible}
				hide={(e)=>{this.setState({visible:false})}}
				width="750px"
				height="500px"
			>
			       <div className="row">
					       	<div className="pop-box-1">
					       		<dl style={{width:'580px'}}>
			       			<dt><span style={{color:'red'}}>*</span>文章标题：</dt>
			       			<dd><input value={this.state.essayTitle.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'')} onChange={this.inputValue.bind()} type="text" placeholder="请输入文章标题" /></dd>
			       		</dl>
			       		<dl style={{width:'580px'}}>
			       			<dt><span style={{color:'red'}}>*</span>文章内容：</dt>
			       			<dd>
			       				<textarea value={this.state.essayNote.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'')} onChange={this.textareaValue.bind()} placeholder="请输入文章内容" ></textarea>
			       			</dd>
			       		</dl>
						   <ul className="up-img clearFix">
							{
									this.state.cover_image.map((item,index)=>{
									return(
										<ImagItem   key={index} index={index} item={item} handleImg={this.handleImg.bind(this)}/>
									)
									})
							}
							{
								this.state.cover_imageBJ.map((item,index)=>{
								return(
									<ImagItem key={index} index={index} item={item} handleImgPath={this.handleImgPath.bind(this)}/>
								)
								})
						    }																																		
							<Dropzone
								multiple={true}
								onDrop={this.chooseImage.bind(this)}
								className = 'choose-image'
								accept="image/jpeg, image/png"
							>												
							<li><label className="file-img">+</label></li>
							</Dropzone>											
				    		</ul>
			       	</div>
			       	<div className="pop-btn">
						   {
							   this.state.checkState==='5'?
							   <Button loading={this.state.loading}  className="btn btn-blue" onClick={(e)=>{this.setState({visible:false})}}>取消</Button>
							   :<Button loading={this.state.loading} className="btn btn-grey layui-layer-close" onClick={()=>this.onSubmit(4)}>保存为草稿</Button>
						   }
						   {
							   (JSON.parse(localStorage.getItem('user')).manageCom).length===1?
                                <Button loading={this.state.loading}  className="btn btn-blue" onClick={()=>this.onSubmit(5)}>发布</Button>:
								<Button loading={this.state.loading}  className="btn btn-blue" onClick={()=>this.onSubmit(3)}>提交到审核</Button>
						   }
			       		
			       	</div>
			       </div>
			</Layer>
			<Layer 
						title = ""
						show={this.state.showLayer} 
						hide={this.deleteArticleIdhideModel.bind(this)}
						width="300px"
						height="150px"
					>
					    <div className="row">
							<div className="pop-box-1">																					
								<p>你确定要删除吗？确定后将不能恢复！</p>										
							</div>
									<div className="pop-btn" style={{padding:'7px 0'}}>
										<Button loading={this.state.loading} onClick={()=>this.deleteArticleIdhideModel()} className="btn btn-blue">取消</Button>
										<Button loading={this.state.loading} className="btn btn-blue" onClick={()=>{this.essayupordetlete(this.state.deleteArticleId,2)}}>确认</Button>
									</div>
						</div>
			</Layer>

				    <div className="line"></div>
				    <Pages totalPage={this.state.totalPage} jump={this.jump.bind(this)}/>
				</div>
			</div>

		)
	}

}
export default ArticleManage

